{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8784a124",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ahocorasick\n",
    "from py2neo import Graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d0b2c4f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def check_words(wds, sent):\n",
    "        for wd in wds:\n",
    "            if wd in sent:\n",
    "                return True\n",
    "        return False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "77092dc5",
   "metadata": {},
   "outputs": [],
   "source": [
    "def classifier(question):\n",
    "    # read keywords\n",
    "    diseases = [i.strip() for i in open(\"dict/disease.txt\") if i.strip()]\n",
    "    departments = [i.strip() for i in open(\"dict/department.txt\") if i.strip()]\n",
    "    checks= [i.strip() for i in open(\"dict/check.txt\") if i.strip()]\n",
    "    drugs= [i.strip() for i in open(\"dict/drug.txt\") if i.strip()]\n",
    "    foods= [i.strip() for i in open(\"dict/food.txt\") if i.strip()]\n",
    "    producers= [i.strip() for i in open(\"dict/producer.txt\") if i.strip()]\n",
    "    symptoms= [i.strip() for i in open(\"dict/symptom.txt\") if i.strip()]\n",
    "    regions = list(set(departments + diseases + checks + drugs + foods + producers + symptoms))\n",
    "    deny_words = [i.strip() for i in open(\"dict/deny.txt\") if i.strip()]\n",
    "    # build field actree\n",
    "    actree = ahocorasick.Automaton()\n",
    "    for index, word in enumerate(regions):\n",
    "        actree.add_word(word, (index, word))\n",
    "    actree.make_automaton()\n",
    "    # build dict\n",
    "    word_dict = dict()\n",
    "    for word in regions:\n",
    "        word_dict[word] = []\n",
    "        if word in diseases:\n",
    "            word_dict[word].append('disease')\n",
    "        if word in departments:\n",
    "            word_dict[word].append('department')\n",
    "        if word in checks:\n",
    "            word_dict[word].append('check')\n",
    "        if word in drugs:\n",
    "            word_dict[word].append('drug')\n",
    "        if word in foods:\n",
    "            word_dict[word].append('food')\n",
    "        if word in symptoms:\n",
    "            word_dict[word].append('symptom')\n",
    "        if word in producers:\n",
    "            word_dict[word].append('producer')\n",
    "    # 问句疑问词\n",
    "    symptom_qwds = ['症状', '表征', '现象', '症候', '表现']\n",
    "    cause_qwds = ['原因','成因', '为什么', '怎么会', '怎样才', '咋样才', '怎样会', '如何会', '为啥', '为何', '如何才会', '怎么才会', '会导致', '会造成']\n",
    "    acompany_qwds = ['并发症', '并发', '一起发生', '一并发生', '一起出现', '一并出现', '一同发生', '一同出现', '伴随发生', '伴随', '共现']\n",
    "    food_qwds = ['饮食', '饮用', '吃', '食', '伙食', '膳食', '喝', '菜' ,'忌口', '补品', '保健品', '食谱', '菜谱', '食用', '食物','补品']\n",
    "    drug_qwds = ['药', '药品', '用药', '胶囊', '口服液', '炎片']\n",
    "    prevent_qwds = ['预防', '防范', '抵制', '抵御', '防止','躲避','逃避','避开','免得','逃开','避开','避掉','躲开','躲掉','绕开',\n",
    "                         '怎样才能不', '怎么才能不', '咋样才能不','咋才能不', '如何才能不',\n",
    "                         '怎样才不', '怎么才不', '咋样才不','咋才不', '如何才不',\n",
    "                         '怎样才可以不', '怎么才可以不', '咋样才可以不', '咋才可以不', '如何可以不',\n",
    "                         '怎样才可不', '怎么才可不', '咋样才可不', '咋才可不', '如何可不']\n",
    "    lasttime_qwds = ['周期', '多久', '多长时间', '多少时间', '几天', '几年', '多少天', '多少小时', '几个小时', '多少年']\n",
    "    cureway_qwds = ['怎么治疗', '如何医治', '怎么医治', '怎么治', '怎么医', '如何治', '医治方式', '疗法', '咋治', '怎么办', '咋办', '咋治']\n",
    "    cureprob_qwds = ['多大概率能治好', '多大几率能治好', '治好希望大么', '几率', '几成', '比例', '可能性', '能治', '可治', '可以治', '可以医']\n",
    "    easyget_qwds = ['易感人群', '容易感染', '易发人群', '什么人', '哪些人', '感染', '染上', '得上']\n",
    "    check_qwds = ['检查', '检查项目', '查出', '检查', '测出', '试出']\n",
    "    belong_qwds = ['属于什么科', '属于', '什么科', '科室']\n",
    "    cure_qwds = ['治疗什么', '治啥', '治疗啥', '医治啥', '治愈啥', '主治啥', '主治什么', '有什么用', '有何用', '用处', '用途',\n",
    "                      '有什么好处', '有什么益处', '有何益处', '用来', '用来做啥', '用来作甚', '需要', '要']\n",
    "    # classify\n",
    "    data = {}\n",
    "    region_wds = []\n",
    "    for i in actree.iter(question):\n",
    "        wd = i[1][1]\n",
    "        region_wds.append(wd)\n",
    "    stop_wds = []\n",
    "    for wd1 in region_wds:\n",
    "        for wd2 in region_wds:\n",
    "            if wd1 in wd2 and wd1 != wd2:\n",
    "                stop_wds.append(wd1)\n",
    "    final_wds = [i for i in region_wds if i not in stop_wds]\n",
    "    medical_dict = {i:word_dict.get(i) for i in final_wds}\n",
    "    if not medical_dict:\n",
    "        return {}\n",
    "    data['args'] = medical_dict\n",
    "    # collect all the needed notes\n",
    "    types = []\n",
    "    for type_ in medical_dict.values():\n",
    "        types += type_\n",
    "    question_type = 'others'\n",
    "    \n",
    "    question_types = []\n",
    "    \n",
    "    # check relationship\n",
    "    if check_words(symptom_qwds, question) and ('disease' in types):\n",
    "        question_type = 'disease_symptom'\n",
    "        question_types.append(question_type)\n",
    "    if check_words(symptom_qwds, question) and ('symptom' in types):\n",
    "        question_type = 'symptom_disease'\n",
    "        question_types.append(question_type)\n",
    "    if check_words(cause_qwds, question) and ('disease' in types):\n",
    "        question_type = 'disease_cause'\n",
    "        question_types.append(question_type)\n",
    "    if check_words(acompany_qwds, question) and ('disease' in types):\n",
    "        question_type = 'disease_acompany'\n",
    "        question_types.append(question_type)\n",
    "    if check_words(food_qwds, question) and ('disease' in types):\n",
    "        deny_status = check_words(deny_words, question)\n",
    "        if deny_status:\n",
    "            question_type = 'disease_not_food'\n",
    "        else:\n",
    "            question_type = 'disease_do_food'\n",
    "        question_types.append(question_type)\n",
    "    if check_words(food_qwds+cure_qwds, question) and 'food' in types:\n",
    "        deny_status = check_words(deny_words, question)\n",
    "        if deny_status:\n",
    "            question_type = 'food_not_disease'\n",
    "        else:\n",
    "            question_type = 'disease_do_food'\n",
    "        question_types.append(question_type)\n",
    "    if check_words(food_qwds+cure_qwds, question) and ('food' in types):\n",
    "        deny_status = check_words(deny_words, question)\n",
    "        if deny_status:\n",
    "            question_type = 'food_not_disease'\n",
    "        else:\n",
    "            question_type = 'food_do_disease'\n",
    "        question_types.append(question_type)\n",
    "    # 推荐药品\n",
    "    if check_words(drug_qwds, question) and 'disease' in types:\n",
    "        question_type = 'disease_drug'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 药品治啥病\n",
    "    if check_words(cure_qwds, question) and 'drug' in types:\n",
    "        question_type = 'drug_disease'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 疾病接受检查项目\n",
    "    if check_words(check_qwds, question) and 'disease' in types:\n",
    "        question_type = 'disease_check'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 已知检查项目查相应疾病\n",
    "    if check_words(check_qwds+cure_qwds, question) and 'check' in types:\n",
    "        question_type = 'check_disease'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    #　症状防御\n",
    "    if check_words(prevent_qwds, question) and 'disease' in types:\n",
    "        question_type = 'disease_prevent'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 疾病医疗周期\n",
    "    if check_words(lasttime_qwds, question) and 'disease' in types:\n",
    "        question_type = 'disease_lasttime'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 疾病治疗方式\n",
    "    if check_words(cureway_qwds, question) and 'disease' in types:\n",
    "        question_type = 'disease_cureway'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 疾病治愈可能性\n",
    "    if check_words(cureprob_qwds, question) and 'disease' in types:\n",
    "        question_type = 'disease_cureprob'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 疾病易感染人群\n",
    "    if check_words(easyget_qwds, question) and 'disease' in types :\n",
    "        question_type = 'disease_easyget'\n",
    "        question_types.append(question_type)\n",
    "\n",
    "    # 若没有查到相关的外部查询信息，那么则将该疾病的描述信息返回\n",
    "    if question_types == [] and 'disease' in types:\n",
    "        question_types = ['disease_desc']\n",
    "\n",
    "    # 若没有查到相关的外部查询信息，那么则将该疾病的描述信息返回\n",
    "    if question_types == [] and 'symptom' in types:\n",
    "        question_types = ['symptom_disease']\n",
    "\n",
    "    # 将多个分类结果进行合并处理，组装成一个字典\n",
    "    data['question_types'] = question_types\n",
    "    \n",
    "    return data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8c9a2fcb",
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_entitydict(args):\n",
    "    entity_dict = {}\n",
    "    for arg, types in args.items():\n",
    "        for type_ in types:\n",
    "            if type_ not in entity_dict:\n",
    "                entity_dict[type_] = [arg]\n",
    "            else:\n",
    "                entity_dict[type_].append(arg)\n",
    "\n",
    "    return entity_dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "1737c19d",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''针对不同的问题，分开进行处理'''\n",
    "def sql_transfer(question_type, entities):\n",
    "    if not entities:\n",
    "        return []\n",
    "\n",
    "    # 查询语句\n",
    "    sql = []\n",
    "    # 查询疾病的原因\n",
    "    if question_type == 'disease_cause':\n",
    "        sql = [\"MATCH (m:Disease) where m.name = '{0}' return m.name, m.cause\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病的防御措施\n",
    "    elif question_type == 'disease_prevent':\n",
    "        sql = [\"MATCH (m:Disease) where m.name = '{0}' return m.name, m.prevent\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病的持续时间\n",
    "    elif question_type == 'disease_lasttime':\n",
    "        sql = [\"MATCH (m:Disease) where m.name = '{0}' return m.name, m.cure_lasttime\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病的治愈概率\n",
    "    elif question_type == 'disease_cureprob':\n",
    "        sql = [\"MATCH (m:Disease) where m.name = '{0}' return m.name, m.cured_prob\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病的治疗方式\n",
    "    elif question_type == 'disease_cureway':\n",
    "        sql = [\"MATCH (m:Disease) where m.name = '{0}' return m.name, m.cure_way\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病的易发人群\n",
    "    elif question_type == 'disease_easyget':\n",
    "        sql = [\"MATCH (m:Disease) where m.name = '{0}' return m.name, m.easy_get\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病的相关介绍\n",
    "    elif question_type == 'disease_desc':\n",
    "        sql = [\"MATCH (m:Disease) where m.name = '{0}' return m.name, m.desc\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病有哪些症状\n",
    "    elif question_type == 'disease_symptom':\n",
    "        sql = [\"MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "\n",
    "    # 查询症状会导致哪些疾病\n",
    "    elif question_type == 'symptom_disease':\n",
    "        sql = [\"MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病的并发症\n",
    "    elif question_type == 'disease_acompany':\n",
    "        sql1 = [\"MATCH (m:Disease)-[r:acompany_with]->(n:Disease) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql2 = [\"MATCH (m:Disease)-[r:acompany_with]->(n:Disease) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql = sql1 + sql2\n",
    "    # 查询疾病的忌口\n",
    "    elif question_type == 'disease_not_food':\n",
    "        sql = [\"MATCH (m:Disease)-[r:no_eat]->(n:Food) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "\n",
    "    # 查询疾病建议吃的东西\n",
    "    elif question_type == 'disease_do_food':\n",
    "        sql1 = [\"MATCH (m:Disease)-[r:do_eat]->(n:Food) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql2 = [\"MATCH (m:Disease)-[r:recommand_eat]->(n:Food) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql = sql1 + sql2\n",
    "\n",
    "    # 已知忌口查疾病\n",
    "    elif question_type == 'food_not_disease':\n",
    "        sql = [\"MATCH (m:Disease)-[r:no_eat]->(n:Food) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "\n",
    "    # 已知推荐查疾病\n",
    "    elif question_type == 'food_do_disease':\n",
    "        sql1 = [\"MATCH (m:Disease)-[r:do_eat]->(n:Food) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql2 = [\"MATCH (m:Disease)-[r:recommand_eat]->(n:Food) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql = sql1 + sql2\n",
    "\n",
    "    # 查询疾病常用药品－药品别名记得扩充\n",
    "    elif question_type == 'disease_drug':\n",
    "        sql1 = [\"MATCH (m:Disease)-[r:common_drug]->(n:Drug) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql2 = [\"MATCH (m:Disease)-[r:recommand_drug]->(n:Drug) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql = sql1 + sql2\n",
    "\n",
    "    # 已知药品查询能够治疗的疾病\n",
    "    elif question_type == 'drug_disease':\n",
    "        sql1 = [\"MATCH (m:Disease)-[r:common_drug]->(n:Drug) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql2 = [\"MATCH (m:Disease)-[r:recommand_drug]->(n:Drug) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "        sql = sql1 + sql2\n",
    "    # 查询疾病应该进行的检查\n",
    "    elif question_type == 'disease_check':\n",
    "        sql = [\"MATCH (m:Disease)-[r:need_check]->(n:Check) where m.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "\n",
    "    # 已知检查查询疾病\n",
    "    elif question_type == 'check_disease':\n",
    "        sql = [\"MATCH (m:Disease)-[r:need_check]->(n:Check) where n.name = '{0}' return m.name, r.name, n.name\".format(i) for i in entities]\n",
    "\n",
    "    return sql"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "1e90f246",
   "metadata": {},
   "outputs": [],
   "source": [
    "def parser(res_classify):\n",
    "    args = res_classify['args']\n",
    "    entity_dict = build_entitydict(args)\n",
    "    question_types = res_classify['question_types']\n",
    "    sqls = []\n",
    "    for question_type in question_types:\n",
    "        sql_ = {}\n",
    "        sql_['question_type'] = question_type\n",
    "        sql = []\n",
    "        if question_type == 'disease_symptom':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'symptom_disease':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('symptom'))\n",
    "\n",
    "        elif question_type == 'disease_cause':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_acompany':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_not_food':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_do_food':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'food_not_disease':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('food'))\n",
    "\n",
    "        elif question_type == 'food_do_disease':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('food'))\n",
    "\n",
    "        elif question_type == 'disease_drug':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'drug_disease':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('drug'))\n",
    "\n",
    "        elif question_type == 'disease_check':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'check_disease':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('check'))\n",
    "\n",
    "        elif question_type == 'disease_prevent':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_lasttime':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_cureway':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_cureprob':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_easyget':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        elif question_type == 'disease_desc':\n",
    "            sql = sql_transfer(question_type, entity_dict.get('disease'))\n",
    "\n",
    "        if sql:\n",
    "            sql_['sql'] = sql\n",
    "\n",
    "            sqls.append(sql_)\n",
    "            \n",
    "    return sqls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "af308189",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''根据对应的qustion_type，调用相应的回复模板'''\n",
    "def answer_prettify(question_type, answers):\n",
    "    num_limit = 20\n",
    "    final_answer = []\n",
    "    if not answers:\n",
    "        return ''\n",
    "    if question_type == 'disease_symptom':\n",
    "        desc = [i['n.name'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}的症状包括：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'symptom_disease':\n",
    "        desc = [i['m.name'] for i in answers]\n",
    "        subject = answers[0]['n.name']\n",
    "        final_answer = '症状{0}可能染上的疾病有：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_cause':\n",
    "        desc = [i['m.cause'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}可能的成因有：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_prevent':\n",
    "        desc = [i['m.prevent'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}的预防措施包括：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_lasttime':\n",
    "        desc = [i['m.cure_lasttime'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}治疗可能持续的周期为：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_cureway':\n",
    "        desc = [';'.join(i['m.cure_way']) for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}可以尝试如下治疗：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_cureprob':\n",
    "        desc = [i['m.cured_prob'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}治愈的概率为（仅供参考）：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_easyget':\n",
    "        desc = [i['m.easy_get'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "\n",
    "        final_answer = '{0}的易感人群包括：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_desc':\n",
    "        desc = [i['m.desc'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0},熟悉一下：{1}'.format(subject,  '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_acompany':\n",
    "        desc1 = [i['n.name'] for i in answers]\n",
    "        desc2 = [i['m.name'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        desc = [i for i in desc1 + desc2 if i != subject]\n",
    "        final_answer = '{0}的症状包括：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_not_food':\n",
    "        desc = [i['n.name'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}忌食的食物包括有：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_do_food':\n",
    "        do_desc = [i['n.name'] for i in answers if i['r.name'] == '宜吃']\n",
    "        recommand_desc = [i['n.name'] for i in answers if i['r.name'] == '推荐食谱']\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}宜食的食物包括有：{1}\\n推荐食谱包括有：{2}'.format(subject, ';'.join(list(set(do_desc))[:num_limit]), ';'.join(list(set(recommand_desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'food_not_disease':\n",
    "        desc = [i['m.name'] for i in answers]\n",
    "        subject = answers[0]['n.name']\n",
    "        final_answer = '患有{0}的人最好不要吃{1}'.format('；'.join(list(set(desc))[:num_limit]), subject)\n",
    "\n",
    "    elif question_type == 'food_do_disease':\n",
    "        desc = [i['m.name'] for i in answers]\n",
    "        subject = answers[0]['n.name']\n",
    "        final_answer = '患有{0}的人建议多试试{1}'.format('；'.join(list(set(desc))[:num_limit]), subject)\n",
    "\n",
    "    elif question_type == 'disease_drug':\n",
    "        desc = [i['n.name'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}通常的使用的药品包括：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'drug_disease':\n",
    "        desc = [i['m.name'] for i in answers]\n",
    "        subject = answers[0]['n.name']\n",
    "        final_answer = '{0}主治的疾病有{1},可以试试'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'disease_check':\n",
    "        desc = [i['n.name'] for i in answers]\n",
    "        subject = answers[0]['m.name']\n",
    "        final_answer = '{0}通常可以通过以下方式检查出来：{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    elif question_type == 'check_disease':\n",
    "        desc = [i['m.name'] for i in answers]\n",
    "        subject = answers[0]['n.name']\n",
    "        final_answer = '通常可以通过{0}检查出来的疾病有{1}'.format(subject, '；'.join(list(set(desc))[:num_limit]))\n",
    "\n",
    "    return final_answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "96707725",
   "metadata": {},
   "outputs": [],
   "source": [
    "def search(sqls):\n",
    "    g = Graph(\"http://localhost:7474\", auth=(\"neo4j\", \"test\"))\n",
    "    final_answers = []\n",
    "    for sql_ in sqls:\n",
    "        question_type = sql_['question_type']\n",
    "        queries = sql_['sql']\n",
    "        answers = []\n",
    "        for query in queries:\n",
    "            ress = g.run(query).data()\n",
    "            answers += ress\n",
    "        final_answer = answer_prettify(question_type, answers)\n",
    "        if final_answer:\n",
    "            final_answers.append(final_answer)\n",
    "    return final_answers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "307719ba",
   "metadata": {},
   "outputs": [],
   "source": [
    "def chatbot(question):\n",
    "    answer = \"没能理解您的意思\"\n",
    "    # 解析句子中含有哪些关键词\n",
    "    res_classify = classifier(question)\n",
    "    print(res_classify)\n",
    "    if not res_classify:\n",
    "        return answer\n",
    "    # 根据句子含义生成对应的sql语句\n",
    "    res_sql = parser(res_classify)\n",
    "    # 查询数据库得到结果，并组合成能阅读的句子\n",
    "    final_answers = search(res_sql)\n",
    "    if not final_answers:\n",
    "        return answer\n",
    "    return '\\n'.join(final_answers)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0454a2c0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'args': {'肺病': ['disease']}, 'question_types': ['disease_desc']}\n",
      "客服机器人: 没能理解您的意思\n"
     ]
    }
   ],
   "source": [
    "# question = input(\"请问您有什么问题呢？\")\n",
    "answer = chatbot(\"肺病的形状是什么\")\n",
    "print(\"客服机器人:\", answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "797099ac",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
